package com.xcc.httpUtils.request;

import com.xcc.httpUtils.utils.StringUtils;
import okhttp3.FormBody;
import okhttp3.Request;
import okhttp3.RequestBody;

import java.util.Map;

/**
 * Created by Carman on 2017/7/7.
 * post 请求
 */
public class PostRequest extends BaseHttpRequest {

    public PostRequest(String url, Object tag, Map<String, String> params, Map<String, String> headers, String json) {
        super(url, tag, params, headers, json);
    }

    @Override
    protected RequestBody buildRequestBody() {
        if (!StringUtils.isEmpty(mJson)) { // 传入 json 使用 json 请求方式
            return RequestBody.create(JSON_MEDIA, mJson);
        }
        // FormBody 的请求头类型为 application/x-www-form-urlencoded;charset=UTF-8, 该类型不支持 json 的传递
        FormBody.Builder builder = new FormBody.Builder();
        addParams(builder);
        FormBody formBody = builder.build();
        return formBody;
    }

    @Override
    protected Request buildRequest(RequestBody requestBody) {
        return builder.post(requestBody).build();
    }

    /**
     * 添加请求参数
     *
     * @param builder
     */
    private void addParams(FormBody.Builder builder) {
        if (params != null) {
            for (String key : params.keySet()) {
                builder.add(key, params.get(key));
            }
        }
    }
}
